﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using DDotNet.Web.UI.AutomatedPageBuilder.Enum;

namespace DDotNet.Web.UI.AutomatedPageBuilder
{
    /// <summary>
    /// Root Class to CRUD Page Builder
    /// </summary>
    public abstract class CRUDPageBuilderBase : Page
    {
        private string _EntityType;
        private Enum.CRUDOperation _CrudOperation;
        private Dictionary<string, string> _EntityPKDefinition;
        
        ///<summary>
        ///Raises the <see cref="E:System.Web.UI.Page.PreInit"></see> event at the beginning of page initialization.
        ///</summary>
        ///
        ///<param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            
            // Load QueryString Parameters
            this.LoadQueryStringParameters();
            
            // Ensure Operation Type and Operation File on Folder
            this.EnsureTypeAndOperation();
        }

        /// <summary>
        /// Ensure Type and Operation Settings File on Directory
        /// </summary>
        private void EnsureTypeAndOperation()
        {
            // Create Objects
            OperationsFileRepositorium.Instance.GetTypeAndOperation(this._EntityType, this._CrudOperation);
        }

        /// <summary>
        /// Load All QueryStrings Parameters
        /// </summary>
        private void LoadQueryStringParameters()
        {
            // Create Object
            string tmpString;
            string[] tmpStringArray;
            
            // Get Entity Type
            if (string.IsNullOrEmpty(this.Request.QueryString[Constants.ENTITY_TYPE_PARAMETER]))
            {
                throw (new ArgumentNullException(string.Format("O parâmetro \"{0}\" que define o tipo da entidade não pode ser encontrado", Constants.ENTITY_TYPE_PARAMETER)));
            }
            else
            {
                this._EntityType = this.Request.QueryString[Constants.ENTITY_TYPE_PARAMETER];
            }
            
            // Get Operation Type
            if (string.IsNullOrEmpty(this.Request.QueryString[Constants.OPERATION_PARAMETER]))
            {
                throw (new ArgumentNullException(string.Format("O parâmetro \"{0}\" que define o tipo da operação a ser realizada não pode ser encontrado", Constants.OPERATION_PARAMETER)));
            }
            else
            {
                try
                {
                    this._CrudOperation = (CRUDOperation) System.Enum.Parse(typeof(CRUDOperation), this.Request.QueryString[Constants.OPERATION_PARAMETER]);
                }
                catch (Exception e)
                {
                    throw (new ArgumentException(string.Format("Não foi possível reconhecer o parâmetro \"{0}\" que define o tipo da operação a ser realizada.", Constants.OPERATION_PARAMETER), e));
                }
            }
            
            // Get Entity PK Definitions
            if (this._CrudOperation == CRUDOperation.Delete || this._CrudOperation == CRUDOperation.Delete)
            {
                if (string.IsNullOrEmpty(this.Request.QueryString[Constants.ENTITY_PK_PARAMETER]))
                {
                    throw (new ArgumentNullException(string.Format("O parâmetro \"{0}\" que define as chaves primárias da entidade não pode ser encontrado", Constants.ENTITY_PK_PARAMETER)));
                }
                else
                {
                    // Get Parameter
                    tmpString = this.Request.QueryString[Constants.ENTITY_PK_PARAMETER];
                    
                    // Split String into Array
                    tmpStringArray = tmpString.Split(';');
                    
                    // Initialize PK's List
                    this._EntityPKDefinition = new Dictionary<string, string>();
                    
                    // Looping on Array Itens
                    foreach (string pkItem in tmpStringArray)
                    {
                        // Add Into EntityPKDefinition
                        this._EntityPKDefinition.Add(pkItem.Split('!')[0],
                                                     pkItem.Split('!')[1]);
                    }
                }
            }
        }
    }
}
